package com.lancoo.lancooknowledgecourseware;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.lancoo.klgcourseware.entity.bean.KlgDbConstant;
import com.stkouyu.LancooSkEgnManager;

import java.io.File;
import java.util.List;

import io.reactivex.disposables.Disposable;
import com.lancoo.lancooknowledgecourseware.entity.CloudPlatformConfigModel;

import lancoo.com.net.retrofitrxjava.NetworkTransformer;
import lancoo.com.net.retrofitrxjava.RxApiManager;
import lancoo.com.net.retrofitrxjava.download.FileDownLoadObserver;
import lancoo.com.net.retrofitrxjava.download.HttpDownManager;
import lancoo.com.net.retrofitrxjava.network.Network;
import lancoo.com.net.retrofitrxjava.subscriber.NormalSubscriber;

public class MainActivity extends AppCompatActivity  {


    private static final String TAG = "MainActivity";
    private List<KlgModel> klgModels;
    private final String URL_APK="http://zh.lancooecp.com:18947/";
    private boolean isfirst=true,isDowning;
    protected ProgressDialog progressDialog;
    protected AlertDialog alertDialog;
    public static String BASE_URL="http://60.190.136.238:18318";
//    public static final String BASE_URL="http://192.168.129.129:10103/Ws_ResourceCloud/";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SharedPreferences sharedPreferences = getSharedPreferences(KlgDbConstant.SP_KNOWLEDGE_COURSE, Context.MODE_PRIVATE);
        int index = sharedPreferences.getInt(KlgDbConstant.SP_TRAIN_INDEX, 0);
        initSpinner(index);
        TextView tv_virsion = findViewById(R.id.tv_version);
//        findViewById(R.id.ll_main).setVisibility(View.INVISIBLE);
        RecyclerView recyclerView = findViewById(R.id.recycler_view);
        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);
        try {
            PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            String versionName = packageInfo.versionName;
            tv_virsion.setText("当前版本:V"+versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        RadioGroup rg_level = findViewById(R.id.rg_level);
        int anInt = sharedPreferences.getInt(KlgDbConstant.SP_TRAIN_LEVEL, -1);
        switch (anInt){
            case 0:
                RadioButton rb_junior = findViewById(R.id.rb_junior);
                rb_junior.setChecked(true);
                break;
            case 1:
                RadioButton rb_middle = findViewById(R.id.rb_middle);
                rb_middle.setChecked(true);
                break;
            case 2:
                RadioButton rb_high = findViewById(R.id.rb_high);
                rb_high.setChecked(true);
                break;
            case -1:
                RadioButton rb_default = findViewById(R.id.rb_default);
                rb_default.setChecked(true);
                break;
        }
        rg_level.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                SharedPreferences sharedPreferences=getSharedPreferences(KlgDbConstant.SP_KNOWLEDGE_COURSE,Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = sharedPreferences.edit();
                int trainLevel=-1;
                switch (checkedId){
                    case R.id.rb_junior:
                        trainLevel=0;
                        break;
                    case R.id.rb_middle:
                        trainLevel=1;
                        break;
                    case R.id.rb_high:
                        trainLevel=2;
                        break;
                    case R.id.rb_default:
                        trainLevel=-1;
                        break;
                }
                edit.putInt(KlgDbConstant.SP_TRAIN_LEVEL,trainLevel);
                edit.apply();
            }
        });


//        loadingDailog = builder.create();
//        Switch switch_btn = findViewById(R.id.switch_btn);
//        switch_btn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                if(isChecked){
//                    KlgDbConstant.klg_baseUrl="http://60.190.136.238:25117/";
//                    KlgDbConstant.examintaionUrl="http://60.190.136.238:18911/";
//                }else{
//                    KlgDbConstant.klg_baseUrl="http://192.168.129.129:8088/";
//                    KlgDbConstant.examintaionUrl="http://192.168.129.129:10156/";
//                }
//            }
//        });
//        if(switch_btn.isChecked()){
//            KlgDbConstant.klg_baseUrl="http://60.190.136.238:18988/";
//            KlgDbConstant.examintaionUrl="http://60.190.136.238:18911/";
//        }else{
//            KlgDbConstant.klg_baseUrl="http://192.168.129.129:8088/";
//            KlgDbConstant.examintaionUrl="http://192.168.129.129:10156/";
//        }
        if (Build.VERSION.SDK_INT >= 23) {
            verifyPermissions(this);
            //  Log.e("6.0以上的版本---->", "获取权限");
        } else {
            // Log.e("6.0以下的版本---->", "不需获取权限");
//            loadingDailog.show();
            versionCode();
        }

        Network.getXmlData(VersionApi.class,"http://60.190.136.238:25102/").getSystemServer("A00").compose(NetworkTransformer.<CloudPlatformConfigModel>commonSchedulers())
                .subscribe(new NormalSubscriber<CloudPlatformConfigModel>(){
                    @Override
                    public void onNext(CloudPlatformConfigModel cloudPlatformConfigModel) {
                        super.onNext(cloudPlatformConfigModel);
                        Log.e("aaaa","onNext,getSystemServer");
                        if(cloudPlatformConfigModel.getSystemServerMsgModels()!=null&&cloudPlatformConfigModel.getSystemServerMsgModels().size()>0){
                            for (CloudPlatformConfigModel.SystemServerMsgModel systemServerMsgModel:cloudPlatformConfigModel.getSystemServerMsgModels()){
//                                KlgDbConstant.klg_baseUrl=systemServerMsgModel.getWsSvrAddr();
//                                KlgDbConstant.examintaionUrl=systemServerMsgModel.getWsSvrAddr();
                                if(!TextUtils.isEmpty(systemServerMsgModel.getSubjectID())&&systemServerMsgModel.getSubjectID().contains("English")){
                                    break;
                                }
                            }
                        }else{
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        Log.e("aaaa","onError,getSystemServer");
                    }
                });

    }




    public void verifyPermissions(Activity activity) {


        if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.RECORD_AUDIO)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED
        ) {
//            Toast.makeText(getApplicationContext(), "没有获取权限,请手动开启权限", Toast.LENGTH_SHORT).show();
            // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
            String[] pressisionArray;
            try {
                pressisionArray = new String[]{Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE,
                         Manifest.permission.READ_PHONE_STATE};
                if (pressisionArray.length == 0) {
                    return;
                }
                Log.e("eeee", "权限不足，请求响应");
                ActivityCompat.requestPermissions(activity, pressisionArray, 100);//,Manifest.permission.READ_PHONE_STATE
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else {
            versionCode();
        }

    }



    private void versionCode(){
        LancooSkEgnManager.getInstance(this).initSkegn(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        RxApiManager.getInstance().removeAll();
        if(progressDialog!=null){
            progressDialog.dismiss();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
//        if(isDowning){
//            startDownLoadNewApk();
//        }
    }


    private void startDownLoadNewApk(){
        isDowning=true;
        showDownLoadProgressDialog();
        HttpDownManager manager = HttpDownManager.getInstance();
        Disposable disposable = manager.downloadFile("http://zh.lancooecp.com:18989/lgftp/apk/knowledgeCourse.apk", Environment.getExternalStorageDirectory().getAbsolutePath(), "knowledgeCourse.apk", new FileDownLoadObserver<File>() {
            @Override
            public void onDownLoadSuccess(File file) {
                Log.e(TAG, "onNext: "+"提示：下载完成" );
                isDowning=false;
                if(progressDialog!=null&&progressDialog.isShowing()){
                    progressDialog.dismiss();
                }
                installNormal(MainActivity.this,file.getPath());
            }

            @Override
            public void onDownLoadFail(Throwable throwable) {
                Log.e(TAG, "失败:"+throwable.toString() );
                if(progressDialog!=null&&progressDialog.isShowing()){
                    progressDialog.dismiss();
                }
                isDowning=false;
                Toast.makeText(MainActivity.this,"抱歉,下载出错了",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onProgress(long progress, long total) {
                Message msg=new Message();
                msg.what=MSG_UPDATA_DOWNLOAD_PROGRESS;
                msg.arg1=(int)progress;
                msg.arg2=(int)total;
                mHandler.sendMessage(msg);

            }
        });
        RxApiManager.getInstance().add(disposable);
        Log.e("aaa",""+URL_APK+"/lgftp/apk/knowledgeCourse.apk");
    }


    private final int MSG_UPDATA_DOWNLOAD_PROGRESS=2;
    private final int MSG_UPDATA_DOWNLOAD_COMPLETE=3;
    private Handler mHandler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what){
                case MSG_UPDATA_DOWNLOAD_PROGRESS:
                    if(progressDialog!=null){
                        progressDialog.setMax(msg.arg2);
                        progressDialog.setProgress(msg.arg1);
                    }
                    break;
                case MSG_UPDATA_DOWNLOAD_COMPLETE:

                    break;
            }
            return false;
        }
    });

    private void showDownLoadProgressDialog(){
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMessage("正在下载更新");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }


    /**
     * 提示安装
     * @param context 上下文
     * @param apkPath apk下载完成在手机中的路径
     */
    private void installNormal(Context context, String apkPath) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
//        Intent intent = new Intent(Build.VERSION.SDK_INT > Build.VERSION_CODES.N_MR1?Intent.ACTION_INSTALL_PACKAGE:Intent.ACTION_VIEW);
        //版本在7.0以上是不能直接通过uri访问的
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
            File file = (new File(apkPath));
            // 由于没有在Activity环境下启动Activity,设置下面的标签
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //参数1:上下文, 参数2:Provider主机地址 和配置文件中保持一致,参数3:共享的文件
            Log.e("aaa","packegeNme:"+getApplicationInfo().packageName);
            Uri apkUri = FileProvider.getUriForFile(context, "lancoo.com.lancooknowledgecourseware.fileprovider", file);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(new File(apkPath)),
                    "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("aaaa","onActivityResult,"+"requestCode:"+requestCode+"，resultCode:"+resultCode);
        if(requestCode==10002){
            if(Build.VERSION.SDK_INT>=26){
                boolean b = getPackageManager().canRequestPackageInstalls();
                if(b){
                    versionCode();
                }
            }
        }
    }


    private void showUpdateMsgDialog(){
        if(alertDialog==null){
            AlertDialog.Builder builder=new AlertDialog.Builder(this,R.style.klg_NoBgColorStyle);
            View inflate = LayoutInflater.from(this).inflate(R.layout.dialog_update_msg, null);
            builder.setView(inflate);
            alertDialog = builder.create();
        }
        alertDialog.show();
    }

    public void updateMsg(View view){
        showUpdateMsgDialog();
    }


    public void word(View  view){
        gotoListActivity("英语单词");
    }
    public void wordword(View  view){
        gotoListActivity("英语词组");
    }
    public void wordwordword(View  view){
        gotoListActivity("英语专有名词");
    }
    public void sentence(View  view){
        gotoListActivity("英语句法");
    }
    public void sentencesentence(View  view){
        gotoListActivity("英语常用表达");
    }
    public void esp(View  view){
        gotoListActivity("ESP");
    }


    private void gotoListActivity(String type){
        Intent mIntent=new Intent(this, KlgListActivity.class);
//        Intent mIntent=new Intent(this,TestActivity.class);
        mIntent.putExtra("klgType",type);
        startActivity(mIntent);
    }

    public static void launch(Context mContext){
        Intent mIntent=new Intent(mContext,MainActivity.class);
        mContext.startActivity(mIntent);
    }
    private static final String[] m={"小学（初级）","初中（初级）","高中（中级）","中职（初级）","高职（中级）","大外（高级）",
            "英专（高级）","研究生（高级）","雅思（高级）","ESP"};
    private void initSpinner(int index){
        Spinner spinner = findViewById(R.id.spinner);
        ArrayAdapter<String> adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item,m);
        //设置下拉列表的风格
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        //将adapter 添加到spinner中
        spinner.setAdapter(adapter);
        spinner.setSelection(index);
        //添加事件Spinner事件监听
        spinner.setOnItemSelectedListener(new SpinnerSelectedListener());

        //设置默认值
        spinner.setVisibility(View.VISIBLE);
    }

    //使用数组形式操作
    class SpinnerSelectedListener implements AdapterView.OnItemSelectedListener {

        public void onItemSelected(AdapterView<?> arg0, View view, int position,
                                   long arg3) {
//            TextView tv=findViewById(R.id.tv_study_level);
//            tv.setText("训练阶段："+m[arg2]);
            TextView tv = (TextView) view;
            tv.setTextColor(Color.RED);
            tv.setGravity(Gravity.CENTER);
            setTrainLevel(MainActivity.this,position);
            findViewById(R.id.ll_type).setVisibility(position==9?View.GONE:View.VISIBLE);
            findViewById(R.id.rl_esp).setVisibility(position!=9?View.GONE:View.VISIBLE);
        }

        public void onNothingSelected(AdapterView<?> arg0) {

        }
    }


    /**
     * 设置当前的训练级别
     *
     */
    private void setTrainLevel(Context mContext, int trainLevel) {
        //设置训练等级
        int trainType ;
        String verisonCode;
        switch (trainLevel) {
            case 0://小学
                trainType = 0;
                verisonCode="A";
                break;
            case 1://初中
                trainType = 0;
                verisonCode="B";
                break;
            case 2://高中
                trainType = 1;
                verisonCode="C";
                break;
            case 3://中职
                trainType = 0;
                verisonCode="D";
                break;
            case 4://高职
                trainType = 1;
                verisonCode="E";
                break;
            case 5: //大学公共英语
                trainType = 2;
                verisonCode="F";
                break;
            case 6://大学英语专业
                trainType = 2;
                verisonCode="H";
                break;
            case 7://研究生公共英语
                trainType = 2;
                verisonCode="J";
                break;
            case 8://雅思
                trainType = 2;
                verisonCode="K";
                break;
            case 9://ESP
                trainType = 2;
                verisonCode="";
                break;
            default:
                trainType =0;
                verisonCode="A";
        }
        SharedPreferences sharedPreferences = mContext.getSharedPreferences(KlgDbConstant.SP_KNOWLEDGE_COURSE, Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sharedPreferences.edit();
        Log.e("eeeee", "当前的知识点课件训练级别是：" + trainType);
        edit.putInt(KlgDbConstant.SP_TRAIN_LEVEL, trainType);
        edit.putInt(KlgDbConstant.SP_TRAIN_INDEX, trainLevel);
        edit.putString(KlgDbConstant.SP_TRAIN_VERSIONCODE, verisonCode);
        edit.apply();
    }


}


